package com.hd.manager.interceptor;

import com.hd.appcommon.entity.Privilege;
import com.hd.hdxgddcommon.utils.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class PrivilegeInterceptor implements HandlerInterceptor {

    private Map<String, String> filterStringMap;

    public PrivilegeInterceptor() {
        filterStringMap = new LinkedHashMap<>();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String requestURL = request.getRequestURL().toString();
        System.out.println(requestURI + " : " + requestURL);
        return false;
    }

    public void addPrivilegePath(List<Privilege> privileges) {
        privileges.forEach(p -> {
                    String privilegeUrl = p.getPrivilegeUrl();
                    String privilegeKey = p.getPrivilegeKey();
                    if (StringUtils.isNotBlank(privilegeUrl, privilegeKey)) {
                        filterStringMap.put(checkPrivilegeUrl(privilegeUrl), privilegeKey);
                    }
                }
        );
    }

    private String checkPrivilegeUrl(String privilegeUrl) {
        if (!privilegeUrl.startsWith("/"))
            return new StringBuilder("/").append(privilegeUrl).toString();
        return privilegeUrl;
    }
}
